package com.gongpingjialoan.activity.loans;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gongpingjialoan.R;
import com.gongpingjialoan.activity.main.BaseActivity;
import com.gongpingjialoan.activity.sell.PhotoSelectorActivity;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.api.Piont;
import com.gongpingjialoan.bean.LoanFinishEB;
import com.gongpingjialoan.bean.PhotoModel;
import com.gongpingjialoan.constant.Const;
import com.gongpingjialoan.manage.PointRecordManage;
import com.gongpingjialoan.network.NetDataJson;
import com.gongpingjialoan.network.UploadCallBack;
import com.gongpingjialoan.utility.LoanUtil;
import com.gongpingjialoan.utility.PhotoUtil;
import com.gongpingjialoan.utility.UploadUtils;
import com.gongpingjialoan.view.GlideRoundTransform;
import com.gongpingjialoan.view.YToXImageView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;

/**
 * 获取贷款凭证/上传身份证
 */
public class LoanCertificateActivity extends BaseActivity implements View.OnClickListener {
    private YToXImageView img_f, img_n;
    private TextView submitT;

    private PopupWindow mPopupWindow;
    private ImageView mCloseLayoutImg;
    private ImageView helpV;
    private View mGetPicLayout, mTakePicLayout;

    private String mPhotoPath;
    private String uplaodUri_0 = "", uplaodUri_1 = "", localPath = "";
    private File dir;
    private static final int REQUEST_IMG_TAKE = 8;
    private static final int REQUEST_CROP = 7;

    private int current_type = 0;//当前选中位置

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loan_certificate);
        initView();
    }


    private void initView() {
        setTitle("获取放款凭证");
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanCardView);
        img_f = (YToXImageView) findViewById(R.id.img_f);
        img_n = (YToXImageView) findViewById(R.id.img_n);
        submitT = (TextView) findViewById(R.id.submit);
        helpV = (ImageView) findViewById(R.id.help);

        img_f.setOnClickListener(this);
        img_n.setOnClickListener(this);
        submitT.setOnClickListener(this);
        helpV.setOnClickListener(this);


//        File file = new File(Environment.getExternalStorageDirectory()
//                + FileConvert.DM_TARGET_FOLDER, "cheeseman");

        dir = new File(Environment.getExternalStorageDirectory()
                + Const.DM_TARGET_FOLDER, "gpj");
        if (!dir.exists()) dir.mkdirs();

        submitT.setBackgroundResource(R.color.text_grey_dark);
        submitT.setEnabled(false);
        initPop();
    }

    private void initPop() {
        View view = LayoutInflater.from(this).inflate(R.layout.include_popup, null);
        view.findViewById(R.id.topview).setVisibility(View.GONE);
        mGetPicLayout = view.findViewById(R.id.layout_get_pic);
        mTakePicLayout = view.findViewById(R.id.layout_take_pic);
        mGetPicLayout.setOnClickListener(this);
        mTakePicLayout.setOnClickListener(this);
        mPopupWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setAnimationStyle(R.style.PopupMenu);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);
        // 需要设置一下此参数，点击外边可消失
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.img_f:
                current_type = 0;
                mPopupWindow.showAtLocation(img_f, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.img_n:
                current_type = 1;
                mPopupWindow.showAtLocation(img_n, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.submit:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.CardApplyClick);
                submit();
                break;
            case R.id.layout_get_pic:
                mPopupWindow.dismiss();
                Intent intent = new Intent(this,
                        PhotoSelectorActivity.class);
                intent.putExtra(PhotoSelectorActivity.KEY_MAX,
                        1);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                startActivityForResult(intent, Const.PICK_PHOTO);
                break;
            case R.id.layout_take_pic:
                mPopupWindow.dismiss();
                mPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                        .getAbsolutePath();
                PhotoUtil.getPhotoFromCamera(this, REQUEST_IMG_TAKE, mPhotoPath);
                break;
            case R.id.help:
                PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanCardTip);
                Intent it = new Intent(mySelf, CertificateDemoActivity.class);
                startActivity(it);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Const.PICK_PHOTO) {
                showProgressDialog("图片上传中...");
                if (data != null && data.getExtras() != null) {
                    List<PhotoModel> photos = (List<PhotoModel>) data.getExtras().getSerializable("photos");
                    if (photos == null || photos.isEmpty()) {
                        Toast.makeText(this, "没有选择图片!", Toast.LENGTH_SHORT).show();
                        hidenProgressDialog();
                    } else {
                        String newPhotoPath = new File(dir, System.currentTimeMillis() + ".jpg")
                                .getAbsolutePath();
                        Bitmap btp = PhotoUtil.getLocalImage(new File(photos.get(0).getOriginalPath()));
                        localPath = newPhotoPath;
                        PhotoUtil.saveLocalImageSquare(btp, new File(newPhotoPath));
                        uploadImg(newPhotoPath);
                    }
                }
            } else if (requestCode == REQUEST_IMG_TAKE) {
                String newtakePath = new File(dir,
                        System.currentTimeMillis() + ".jpg").getAbsolutePath();

                String path = PhotoUtil.onPhotoFromCamera(this, REQUEST_CROP, mPhotoPath, 3,
                        2, 300, newtakePath);
                localPath = path;

            } else if (requestCode == REQUEST_CROP) {
                showProgressDialog("图片上传中...");
//                localPath = mPhotoPath;


                uploadImg(localPath);

            }
        }
    }

    private void uploadImg(String path) {
        Log.d("aa", "222222222222222222222");
        UploadUtils.uploadImage(path, new UploadCallBack() {
            @Override
            public void success(final String uri) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hidenProgressDialog();
                        if (current_type == 0) {
                            uplaodUri_0 = uri;
                            Glide.with(mySelf).load(localPath).transform(new GlideRoundTransform(mySelf)).into(img_f);
                        } else {
                            uplaodUri_1 = uri;
                            Glide.with(mySelf).load(localPath).transform(new GlideRoundTransform(mySelf)).into(img_n);
                        }

                        if (!TextUtils.isEmpty(uplaodUri_0) && !TextUtils.isEmpty(uplaodUri_1)) {
                            submitT.setBackgroundResource(R.color.blue_3fbbff);
                            submitT.setEnabled(true);
                        }
                    }
                });

            }

            @Override
            public void failure() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        hidenProgressDialog();
                        Toast.makeText(mySelf, "上传图片失败, 请重试", Toast.LENGTH_SHORT).show();

                    }
                });
            }
        }, API.uploadHeadPic, "image");
    }

    private void submit() {
        showProgressDialog();
        NetDataJson netDataJson = new NetDataJson(new NetDataJson.OnStringListener() {
            @Override
            public void onDataJsonError(String errorMessage) {
                hidenProgressDialog();
                Toast.makeText(mySelf, errorMessage, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDataJsonUpdate(String json) {
                hidenProgressDialog();
                try {
                    JSONObject jo = new JSONObject(json);
                    if (jo == null) {
                        return;
                    }
                    if ("error".equals(jo.getString("status"))) {
                        Toast.makeText(mySelf, jo.getString("msg"), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    PointRecordManage.getInstance().addPoint(mySelf, Piont.CardApplySuccess);
                    LoanUtil.toLoanData(json);
                    LoanUtil.goToPerfect(mySelf);
                    EventBus.getDefault().post(new LoanFinishEB());
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, 1);

        netDataJson.setUrl(NetDataJson.LOAN_SERVER_DOMAIN + API.perfect_evaluations + "?source=chefenqi-android");
        netDataJson.setUseOtherDomain(true);
        netDataJson.addParam("step", "uploadIDCard");
        netDataJson.addParam("photo_front", uplaodUri_0);
        netDataJson.addParam("photo_back", uplaodUri_1);
        netDataJson.request("put");
    }

    @Override
    public void finish() {
        super.finish();
        PointRecordManage.getInstance().addPoint(mySelf, Piont.LoanCardBack);
    }
}
